package com.sumer.pool;

import java.util.concurrent.*;

/**
 * JDK线程池
 */
public class ThreadPoolTest {

    public static void main(String[] args) {
        // 创建线程池的三个方法
        // 1. 只会创建一个线程
        // ExecutorService service = Executors.newSingleThreadExecutor();
        // 固定大小的线程池
//         ExecutorService service = Executors.newFixedThreadPool(5);
        // 可自动调整
//        ExecutorService service = Executors.newCachedThreadPool();
        ExecutorService service = new ThreadPoolExecutor(5, Runtime.getRuntime().availableProcessors(), 5,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());
        try {
            // 使用
            for (int i = 0; i < 100; i++) {
                service.execute(() -> {
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭
            service.shutdown();
        }
    }
}
